package com.wuyou.controller;

import cn.hutool.json.JSONUtil;
import com.wuyou.domain.po.Advertising;
import com.wuyou.service.IAdvTypeService;
import com.xxl.job.core.biz.model.ReturnT;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * description 定时查看广告缓存数据是否有效
 * author 刘雷雨
 * date 2022/10/3 10:29
 * version 1.0
 **/
@Component
public class TimerController {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private IAdvTypeService advTypeService;

    @Scheduled(cron = "*/5 * * * * ?")//"{秒数} {分钟} {小时} {日期} {月份} {星期} {年份(可为空)}
    public ReturnT getAllUserRegisterTime() {
        //获取当前系统时间
        long now = System.currentTimeMillis();
        //扫描key为"advertising_score"的zset中时间在0 ~ now 当前时间范围内的数据
        Set<String> advTime = redisTemplate.opsForZSet().rangeByScore("advertising_score", 0, now);
        HashOperations<String, Object, Object> redisHash = redisTemplate.opsForHash();
        //遍历set集合
        for (String adv : advTime) {
            //判断当前key是否存在
            Boolean hasKey = redisHash.hasKey("advertising", adv);
            if (hasKey) {
                Advertising advertising = JSONUtil.toBean((String) redisHash.get("advertising", adv), Advertising.class);
                //修改广告栏位信息
                advTypeService.updateAdvRegion(advertising.getAdvTypeId(),"0");
                //删除当前key的数据
                redisHash.delete("advertising",adv);
                redisTemplate.opsForZSet().remove("advertising_score",adv);
            }
        }
        return ReturnT.SUCCESS;
    }
}
